﻿using System.Linq;
using System.Threading.Tasks;
using JoyfulHomeJourney.BackEnd.Infrastructure.Atrributes;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses.Objects;
using JoyfulHomeJourney.BackEnd.Server.EFCore;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Responses;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace JoyfulHomeJourney.BackEnd.Server.Instances
{
    internal class ProductEF
    {
        public ProductEF(DbContext dbContext)
        {
            sysProductsServerEF = new SysProductsServerEF(dbContext);
            sysCarServicesServerEF = new SysCarServicesServerEF(dbContext);
            sysCarSuppliesServerEF = new SysCarSuppliesServerEF(dbContext);
        }
        public SysProductsServerEF sysProductsServerEF { get; set; }
        public SysCarSuppliesServerEF sysCarSuppliesServerEF { get; set; }
        public SysCarServicesServerEF sysCarServicesServerEF { get; set; }
    }
    [InjectClass]
    public class SysProductServer : ISysProductServer
    {
        private readonly ProductEF _productEF;

        public SysProductServer(DbContext dbContext)
        {
            _productEF = new ProductEF(dbContext);
        }
        public async Task<ResponseApiDto> PaginationAsync(int page, int limit, string key, string carShopId, string category)
        {
            int total = 0;
            var data = await _productEF.sysProductsServerEF.Pagination1(d => (string.IsNullOrEmpty(key) || d.PName.Contains(key)) && (carShopId == null || d.PCsId == carShopId) && (category == null || d.PCategory == category), false, d => d.PCreateAt, out total, page, limit).ToListAsync();
            var responseData = data.Select(d => d.ToResponseDto()).ToList();
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = responseData, total = total });
        }

        public async Task<ResponseApiDto> Detail(string id)
        {
            var product=await _productEF.sysProductsServerEF.Query(d => d.PId == id).SingleOrDefaultAsync();
            ResponseSysProductsDto responseDto = null;
            switch (product.PCategory)
            {
                case "sys_car_supplies":
                    var supplies = await _productEF.sysCarSuppliesServerEF.Query(d => d.CsProductId == product.PId).SingleOrDefaultAsync();
                    responseDto = supplies.ToResponseDto(product);
                    break;
                case "car_services":
                    var services = await _productEF.sysCarSuppliesServerEF.Query(d => d.CsProductId == product.PId).SingleOrDefaultAsync();
                    responseDto = services.ToResponseDto(product);
                    break;
            }
           return ResponseApiDto.Success("数据已获取",responseDto);
        }

    }
}
